package net.jueb.frameworkDemo.mq.activeMq.ps;

import java.util.Scanner;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *生产者消费者模式：生产者生产消息放到队列里，多个消费者同时监听队列，谁先抢到消息谁就会从队列中取走消息；即对于每个消息只能被最多一个消费者拥有。
 *
 * activemq 生产者实例
 */
public class ProducerApp {
	private static final Logger log = LoggerFactory.getLogger(ProducerApp.class);
//	private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	private static final String BROKER_URL = "failover://tcp://192.168.0.205:61616";
	private static final String SUBJECT = "test-activemq-queue";

	
	
	
	public static void main(String[] args) throws JMSException {
		// 初始化连接工厂
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
		// 获得连接
//		Connection conn = connectionFactory.createConnection();
		Connection conn = connectionFactory.createConnection("admin", "admin");
		conn.setExceptionListener(new ExceptionListener() {
			@Override
			public void onException(JMSException arg0) {
				log.error(arg0.getMessage());
				System.err.println(arg0.getMessage());
			}
		});
		// 启动连接
		conn.start();

		// 创建Session，此方法第一个参数表示会话是否在事务中执行，第二个参数设定会话的应答模式
		Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列
		Destination dest = session.createQueue(SUBJECT);
		// 通过session可以创建消息的生产者
		MessageProducer producer = session.createProducer(dest);
		for (int i = 0; i < 1000; i++) 
		{
			// 初始化一个mq消息
			TextMessage message = session.createTextMessage("hello active mq 中文" + i);
			log.debug("send:"+i);
			// 发送消息
			producer.send(message);
			log.debug("sended:"+i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}
		new Scanner(System.in).nextLine();
		// 关闭mq连接
		conn.close();
	}
}
